<template>
  <!-- <div class="player-layer" :class="{'player-layer-open': isOpen}"> -->
  <!-- <div class="player-layer" :class="getOpenclass()" ref="MusicPlayerUI"> -->
  <div class="player-layer" :style="getOpenStyle">
    <div class="player-container">
      <div class="player-hide-box" :class="{'player-hide-box-open': isShowList}">
        <!--歌单栏-->
        <section class="player-header">
          <div class="play-title">Music Player & {{MusicList[NowPlayIndex].name}} -
            {{MusicList[NowPlayIndex].artist}}<span class="album-name"></span></div>
          <!--
            搜索功能（没啥用，去掉）
          <div class="player-music-search">
            <form method="get" class="music-search-form" action="https://firpe.cn" role="search">
              <span class="ea-icon ea-search"></span>
              <input type="search" name="ms" class="music-search-input" size="26" placeholder="搜索" />
            </form>
          </div>
          -->

        </section>
        <!--音乐列表栏-->
        <section class="player-info">
          <div class="history-record">
            <ul class="history-list">
              <li class="now" data-id="2358582640" data-source="netease" data-type="0">「Welcome」默认的曲单</li>
            </ul>
          </div>
          <div class="current-record">
            <ul class="play-list">
              <!--此处显示音乐列表-->
              <li v-for="(item,index) in MusicList" class="li-title" @click="btnMusicListItem(index)">
                <span>{{index + 1 + '. '}} {{item.name}} - {{item.artist}}</span></li>
            </ul>
          </div>
          <!--歌词栏-->
          <div class="lyric-text">
            <div id="lrcWrap" class="lrc-wrap lrc-wrap-open">
              <div id="lrcBox" class="lrc-box">
                <div id="lrc_2">
                  <ul
                    style="height: 350px; list-style: none; position: relative; line-height: 30px; padding: 0px 15px; overflow-y: hidden; display: block; width: auto; text-align: left;">
                    <li class="geci_moonlight" lang="">暂无歌词</li>
                  </ul>
                </div>
              </div>
            </div>
            <div class="lyric-script"></div>
          </div>
          <!--图片栏-->
          <div class="cover-photo">
            <div class="cover-disc"><img src="./images/bg.jpg"></div>
          </div>
          <div class="bg-player"></div>
          <div class="bg-player-mask"></div>
        </section>
      </div>

      <!--上一首、播放、下一首 按钮-->
      <div class="player-control">
        <div class="btn-prev ea-icon" @click="btnprev()"><i class="ea-prev"></i></div>
        <div class="btn-play ea-icon" @click="btnplay()"><i :class="{'ea-play': !isPlay , 'ea-pause': isPlay}"></i>
        </div>
        <div class="btn-next ea-icon" @click="btnnext()"><i class="ea-next"></i></div>

        <!--音乐进度显示-->
        <div class="player-progress">
          <div class="progress-sider">
            <div class="sider-loaded" @click="btnsetNowProgress($event)" style="width:100%"></div>
            <div class="sider-pace SlowMotion" @click="btnsetNowProgress($event)" :style="{width: getProgres + '%'}">
            </div>
            <a class="ui-slider-handle ui-state-default ui-corner-all SlowMotion" href="#"
              :style="{left: getProgres + '%' }"></a>
          </div>

          <!--音乐标题、作者-->
          <div class="song-info">
            <span class="song-title">{{MusicList[NowPlayIndex].name}}</span>
            <span class="song-artist">{{' - ' + MusicList[NowPlayIndex].artist}}</span>
          </div>
        </div>
        <div class="player-timer">{{SecondToDate(NowProgress)}}/{{SecondToDate(TotalProgress)}}</div>

        <!--循环按钮-->
        <div class="btn-mode ea-icon" @click="btnplaymodel()">
          <i :class="{'ea-all': PlayModel=='all' , 'ea-shuffle': PlayModel=='shuffle' , 'ea-onec': PlayModel=='onec'}">
          </i>
        </div>

        <!--下载按钮-->
        <div class="btn-download ea-icon" @click="btndownload()"><i class="ea-download"></i></div>

        <!--展开播放列表按钮-->
        <div class="btn-enlarge ea-icon" @click="btnenlarge()"><i class="ea-enlarge"></i></div>
        <div class="player-volume ea-icon">
          <div class="volume-mute">
            <!--静音按钮-->
            <i @click="btnMuted()" :class="{'ea-volume': !isMuted, 'ea-mute': isMuted}"></i>
          </div>

          <!--音量滑动条-->
          <div class="volume-sider" @click="btnsetVolume($event)">
            <div class="sider-pace" :style="{width: NowVolume + '%'}"></div>
            <a class="ui-slider-handle ui-state-default ui-corner-all SlowMotion" style="cursor:pointer "
              @mousedown="move" :style="{left: NowVolume + '%'}"></a>
          </div>
        </div>

        <!--展开/收缩播放器按钮-->
        <div class="btn-eaplayer" @click="btnOpenplayer()">
          <i class="ea-icon" :class="{'ea-right': !isOpen, 'ea-left': isOpen}"></i>
        </div>

      </div>
    </div>
    <!--     <audio id="audio" :autoplay="this.AutoPlay == 'false' ? 'autoplay' : ''" :src="MusicList[NowPlayIndex].src"
      type="audio/mpeg" ref="MusicPlay"></audio> -->
    <audio id="audio" :src="MusicList[NowPlayIndex].src" type="audio/mpeg" ref="MusicPlay"></audio>
  </div>
</template>

<style>
  @import './assets/css/eaplayer.css';
</style>

<script>
  import { getMusicList, getMusicinfo, getMusicdetailinfo } from './assets/js/network'

  export default {
    name: 'EAPLAYER',
    props: {
      MusicList: {
        type: Array,
        default: function () {
          return [
            {
              name: '当前无音乐列表',
              artist: '请检查您的播放歌单',
              src: ''
            }
          ]
        }
      },
      AutoPlay: {
        type: Boolean,
        default: false
      },
      PlayModel: {
        type: String,
        default: 'shuffle'
      },
      playlist: {
        type: String,
        default: '2358582640'
      }
    },
    data() {
      return {
        isOpen: false,
        isShowList: false,
        isPlay: false,
        isMuted: false,
        NowPlayIndex: 0,
        NowProgress: 0,
        TotalProgress: 0,
        NowVolume: 100,
      }
    },
    components: {
    },
    //页面创建后
    created() {
      console.log(this.AutoPlay == 'false' ? 'autoplay' : '');

      /*
      new Promise((resolve, reject) => {
            }).then(res => {
              //对结果进行处理
              return res + 1;
            }).then(res => {
              //对结果进行处理
              return res + 1;
            }).then(res => {
              //对结果进行处理
              return res + 1;
            }).catch(err =>{
            }) */

      //请求网易云音乐 歌单
      getMusicList(this.playlist).then(res => {
        //console.log(res);
        setTimeout(() => {
          for (let i = 0; i < res.data.playlist.trackIds.length; i++) {
            //请求音乐播放直链
            setTimeout(() => {
              getMusicinfo(res.data.playlist.trackIds[i].id).then(res2 => {
                //请求音乐名称、歌手信息
                setTimeout(() => {
                  getMusicdetailinfo(res.data.playlist.trackIds[i].id).then(res3 => {
                    let list = {
                      name: res3.data.songs[0].name,
                      artist: res3.data.songs[0].ar[0].name,
                      src: res2.data.data[0].url
                    }
                    this.MusicList.push(list);
                    if (this.MusicList[0].name == "当前无音乐列表") {
                      this.MusicList.splice(0, 1)
                    }
                  }).catch(err => {
                    console.log("音乐信息请求错误");
                  })
                }, 2000)
              }).catch(err => {
                console.log("音乐ID请求错误");
              })
            }, 0)
          }
        }, 0)
      })
      this.$nextTick(() => {
        if (this.PlayModel == 'all' || this.PlayModel == 'onec') {
          this.NowPlayIndex = 0;
        } else if (this.PlayModel == 'shuffle') {
          console.log(this.MusicList.length);
          this.NowPlayIndex = this.randomNum(0, this.MusicList.length);
        }
      })
    },
    //页面挂载后
    mounted() {
      //禁止循环，否则无法触发ended事件
      this.$refs.MusicPlay.loop = false
      this.ChangeProgress()
      this.$refs.MusicPlay.addEventListener('ended', this.PlayEndedHandler, false);
      if (this.AutoPlay == true) { this.isPlay = true; }
    },
    //计算属性：属性名称(){} （调用时不需要加小括号）
    computed: {
      //获取当前播放进度
      getProgres() {
        return 100 * (this.NowProgress / this.TotalProgress);
      },
      getOpenStyle() {
        if (this.isOpen == true) return { left: '0px' }
      }
    },
    methods: {
      getOpenclass() {
        if (this.isOpen == false) {
          return { left: '-94%' }
        } else {
          return { left: '0px' }
        }
      },
      // 生成一个随机数
      randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
      },
      //展开/隐藏侧边栏播放器
      btnOpenplayer() {
        this.isShowList = false;
        this.isOpen = !this.isOpen;
      },
      //展开/隐藏播放列表
      btnenlarge() {
        this.isShowList = !this.isShowList;
      },
      //播放模式按钮
      btnplaymodel() {
        if (this.PlayModel == 'all') {
          this.PlayModel = 'shuffle';
        } else if (this.PlayModel == 'shuffle') {
          this.PlayModel = 'onec';
        } else if (this.PlayModel == 'onec') {
          this.PlayModel = 'all'
        }
      },
      //上一首按钮
      btnprev() {
        if (this.PlayModel == 'all' || this.PlayModel == 'onec') {
          this.NowPlayIndex = this.NowPlayIndex - 1;
          if (this.NowPlayIndex <= -1) {
            this.NowPlayIndex = 0;
          }
        } else if (this.PlayModel == 'shuffle') {
          this.NowPlayIndex = this.randomNum(0, this.MusicList.length);
        }
        this.btnMusicListItem(this.NowPlayIndex)
      },
      //播放/暂停按钮
      btnplay() {
        if (this.isPlay == false) {
          this.$refs.MusicPlay.play();
          this.isPlay = true;
        } else if (this.isPlay == true) {
          this.$refs.MusicPlay.pause();
          this.isPlay = false;
        }
      },
      //下一首按钮
      btnnext() {
        if (this.PlayModel == 'all' || this.PlayModel == 'onec') {
          this.NowPlayIndex = this.NowPlayIndex + 1;
          if (this.NowPlayIndex >= this.MusicList.length) {
            this.NowPlayIndex = 0;
          }
        } else if (this.PlayModel == 'shuffle') {
          this.NowPlayIndex = this.randomNum(0, this.MusicList.length);
        }
        this.btnMusicListItem(this.NowPlayIndex)
      },
      //下载音乐按钮
      btndownload() {
        window.open(this.$refs.MusicPlay.currentSrc, '_blank')
      },
      //静音/启用按钮
      btnMuted() {
        this.isMuted = !this.isMuted;
        this.$refs.MusicPlay.muted = this.isMuted;
        if (this.isMuted == true) {
          this.NowVolume = 0;
        } else {
          this.NowVolume = 100;
        }
      },
      //点击播放列表
      btnMusicListItem(index) {
        this.NowPlayIndex = index;
        this.$refs.MusicPlay.load();
        this.NowProgress = 0;
        this.TotalProgress = 0;
        var playPromise = this.$refs.MusicPlay.play();
        if (playPromise) {
          playPromise.then(() => {
          }).catch((e) => {
            // 失败后继续回调
            this.btnMusicListItem(index);
          });
        }
        this.isPlay = true;
      },
      //改变当前播放时间
      btnsetNowProgress(e) {
        const setbfb = e.offsetX / e.path[0].scrollWidth;
        this.$refs.MusicPlay.currentTime = this.TotalProgress * setbfb;
      },
      //改变当前音量
      btnsetVolume(e) {
        const setbfb = e.offsetX / e.path[0].scrollWidth;
        this.NowVolume = this.NowVolume * setbfb
        this.$refs.MusicPlay.volume = (this.NowVolume * setbfb) / 100;
      },
      //改变时间文本
      ChangeProgress() {
        const timer = setInterval(() => {
          try {
            this.NowProgress = this.$refs.MusicPlay.currentTime;
            this.TotalProgress = this.$refs.MusicPlay.duration;
          } catch (error) {
            this.NowProgress = '0:00';
            this.TotalProgress = '0:00';
          }
        }, 1000)
      },
      //格式化时间文本
      SecondToDate(msd) {
        const date = new Date(msd * 1000)
        return this.formatDate(date, 'mm:ss')
      },
      formatDate(date, fmt) {
        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        let o = {
          'M+': date.getMonth() + 1,
          'd+': date.getDate(),
          'h+': date.getHours(),
          'm+': date.getMinutes(),
          's+': date.getSeconds()
        };
        for (let k in o) {
          if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str));
          }
        }
        return fmt;
      },
      padLeftZero(str) {
        return ('00' + str).substr(str.length);
      },

      //音乐播放结束监听
      PlayEndedHandler() {
        this.btnnext();
      },
      move(e) {
        //获取目标元素
        let odiv = e.target;
        //算出鼠标相对元素的位置
        let disX = e.clientX - odiv.offsetLeft;
        //鼠标按下并移动的事件
        document.onmousemove = (e) => {
          //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
          let left = e.clientX - disX;
          if (left >= 0 && left <= 100) {
            //绑定元素位置到positionX和positionY上面
            this.positionX = top;
            //移动当前元素
            odiv.style.left = left + 'px';
            //改变音量
            this.NowVolume = left
            this.$refs.MusicPlay.volume = (left) / 100;
          }
        };
        document.onmouseup = (e) => {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      }
    },
  }
</script>